* Author: Enno Schröder

/*
The script has three parts. 

1) Import Excel files (results of IO analysis), merge with Penn World Tables, and save dta file on disk
2) Use dta file and prepare analysis data (create variables etc.)
3) Several sections that make up the exploratory analysis and the regressions (creating the tables and figures)

When running the whole script (ctrl + D), only the second part is executed.
The first part is commented out, and the third part appears below the exit command.
*/

* Set working dir 
* cd ".....................\replicationpack"

* PART 1

*-------------------------------------------------------------------------------
* Import Matlab results (Excel sheets), merge with PWT, and save dta files on disk
*-------------------------------------------------------------------------------

/*
import excel ".\io_result\io_result_all_with_notes.xlsx", sheet("country") firstrow case(lower) clear
rename (grossimport-heege) (=_incl)
keep country year *_incl household
save "io_result_all.dta", replace

import excel ".\io_result\io_result_wo_primary_with_notes.xlsx", sheet("country") firstrow case(lower) clear
keep country year grossimport-heege
save "io_result_wo_primary.dta", replace

merge 1:1 country year using io_result_all
drop _merge

rename country countrycode

merge 1:1 countrycode year using .\pwt\pwt91
drop if _merge == 2
drop _merge

drop currency_unit emp-cwtfp rconna-pl_k 

rename countrycode cc
rename country cn

order cc cn year
sort cc year

* Check 
tab year
tab cc

save merged_data, replace  // The code below uses this file and creates the needed variables
*/

* PART 2

*-------------------------------------------------------------------------------
* Prepare analysis data (create variables etc.)
*-------------------------------------------------------------------------------

use merged_data, clear

* Convert all vars to Gt
foreach x of varlist grossimport-household {
	replace `x' = `x'/1000
}

* New emission variables and new variable names
gen PBE = pbe_incl + household
gen CBE = PBE + eefi_incl - eefe_incl

gen EX = eefe_incl
gen EM = eefi_incl
gen EGX = eege_incl
gen EGM = eegi_incl

gen onshore  = eege
gen offshore = eagi
gen onshore_sa = heege

* PBE adjusted for trade 
gen PBEadj = PBE - onshore + offshore
gen PBEadj_incl = PBE - EGX + eagi_incl

* Emission balances 
gen levBEET  = EX - EM
gen levBEEGT = EGX - EGM
gen levnetonshore = onshore - offshore
gen levnetonshore_sa = onshore_sa - offshore
gen levnetonshore_incl = eege_incl - eagi_incl

* Emission balances in percent of PBE
foreach x in BEET BEEGT netonshore netonshore_sa netonshore_incl {
    gen `x' = lev`x'/PBE*100	
}

* Income per capita
gen income = rgdpo/(pop*1000)  // Thousand dollars per person
gen logincome = log(income)

* Population in 2000
gen temp = pop if year==2000
egen pop2000 = mean(temp), by(cc)
drop temp

* Set panel data
sort cc year
encode cc, gen(id)  // Create new numeric id with value labels
xtset id year
order id cc year

label var income "Income"
label var logincome "Log income"

set seed 1000  // To replicate bootstrap standard errors

set scheme plotplainblind  // To replicate graphs

exit  // Execution stops here. 

* PART 3 

* Before executing the commands of each section, hit ctrl + D to "re-fresh" the analysis data.

*-------------------------------------------------------------------------------
* Summary stats: Table 3 (Appendix)
*-------------------------------------------------------------------------------

tabstat netonshore netonshore_sa income if income!=., stat(mean N min p10 p25 p50 p75 p90 max) col(stat) 

tabstat netonshore netonshore_sa income if income!=. & pop2000>10, stat(mean N min p10 p25 p50 p75 p90 max) col(stat) 

*-------------------------------------------------------------------------------
* Line plot: Figure 1: Emission Offshoring in Eight Large Economies 2000--2014
*-------------------------------------------------------------------------------

label var levBEET "BEET"
label var levnetonshore "Net onshoring"
label var levnetonshore_sa "Net onshoring, scale-adjusted"

line levnetonshore levnetonshore_sa levBEET year if inlist(cc, "USA", "DEU", "JPN", "CHN", "IND", "GBR", "FRA", "ITA"), ///
	by(cn, col(3) note("") yrescale graphregion(margin(0 0 0 0)) scale(1.2) legend(at(3))) ///
	xtitle("") xsize(15) ysize(10) legend(col(1)) ylabel(, angle(vertical)) yline(0, lpattern(solid)) subtitle(, size(small))
gr export .\figures\line_offshoring_8countries.pdf, replace

*-------------------------------------------------------------------------------
* Line plot: Figure 2: Trade-Adjusted PBE in Eight Large Economies 2000--2014
*-------------------------------------------------------------------------------

label var PBEadj "Trade-adjusted PBE"

line PBEadj PBE year if inlist(cc, "USA", "DEU", "JPN", "CHN", "IND", "GBR", "FRA", "ITA"), ///
	by(cn, col(3) note("") yrescale graphregion(margin(0 0 0 0)) scale(1.2) legend(at(3))) ///
	xtitle("") xsize(15) ysize(10) legend(col(1)) ylabel(, angle(vertical)) subtitle(, size(small))
gr export .\figures\line_pbe_adjusted_8countries.pdf, replace

*-------------------------------------------------------------------------------
* Line plot: Figure 5: Trade-Adjusted PBE in Eight Major Economies 2000–2014, Including the Primary Sector
*-------------------------------------------------------------------------------

label var PBEadj_incl "Trade-adjusted PBE"

line PBEadj_incl PBE year if inlist(cc, "USA", "DEU", "JPN", "CHN", "IND", "GBR", "FRA", "ITA"), ///
	by(cn, col(3) note("") yrescale graphregion(margin(0 0 0 0)) scale(1.2) legend(at(3))) ///
	xtitle("") xsize(15) ysize(10) legend(col(1)) ylabel(, angle(vertical)) subtitle(, size(small))
gr export .\figures\line_pbe_adjusted_incl_8countries.pdf, replace

*-------------------------------------------------------------------------------
* Table 1: Net Onshoring vs. Income, Regressions
*-------------------------------------------------------------------------------

reg netonshore income if year==2014, vce(robust)
est sto OLS_ALL

reg netonshore income if year==2014 & pop2000>10, vce(robust)
est sto OLS_BIG

xtreg netonshore income , be vce(bootstrap, reps(1000))
est sto BTW_ALL

xtreg netonshore income if pop2000>10, be vce(bootstrap, reps(1000))
est sto BTW_BIG

reg netonshore income b2014.year, vce(cluster id)
est sto POLS_ALL

reg netonshore income b2014.year if pop2000>10, vce(cluster id)
est sto POLS_BIG

esttab OLS_ALL OLS_BIG BTW_ALL BTW_BIG POLS_ALL POLS_BIG, stats(N r2, fmt(0 3) label(N Rsq)) se label indicate("Time effects = *.year")

esttab OLS_ALL OLS_BIG BTW_ALL BTW_BIG POLS_ALL POLS_BIG using .\tables\regtable-offshoring, ///
	stats(N r2, fmt(0 3) label(N R2)) se label booktabs nofloat nonotes replace ///
	mtitle(OLS_ALL OLS_BIG BTW_ALL BTW_BIG POLS_ALL POLS_BIG) indicate("Time effects = *.year") 

*-------------------------------------------------------------------------------
* Table 2: Scale-Adjusted Net Onshoring vs. Income, Regressions
*-------------------------------------------------------------------------------

reg netonshore_sa income if year==2014, vce(robust)
est sto OLS_ALL

reg netonshore_sa income if year==2014 & pop2000>10, vce(robust)
est sto OLS_BIG

xtreg netonshore_sa income , be vce(bootstrap, reps(1000))
est sto BTW_ALL

xtreg netonshore_sa income if pop2000>10, be vce(bootstrap, reps(1000))
est sto BTW_BIG

reg netonshore_sa income b2014.year, vce(cluster id)
est sto POLS_ALL

reg netonshore_sa income b2014.year if pop2000>10, vce(cluster id)
est sto POLS_BIG

esttab OLS_ALL OLS_BIG BTW_ALL BTW_BIG POLS_ALL POLS_BIG, stats(N r2, fmt(0 3) label(N Rsq)) se label indicate("Time effects = *.year")

esttab OLS_ALL OLS_BIG BTW_ALL BTW_BIG POLS_ALL POLS_BIG using .\tables\regtable-offshoring-baltrade, ///
	stats(N r2, fmt(0 3) label(N R2)) se label booktabs nofloat nonotes replace ///
	mtitle(OLS_ALL OLS_BIG BTW_ALL BTW_BIG POLS_ALL POLS_BIG) indicate("Time effects = *.year") 

*-------------------------------------------------------------------------------
* Table 5 (Appendix): BEET vs. Income, Regressions
*-------------------------------------------------------------------------------

reg BEET income if year==2014, vce(robust)
est sto OLS_ALL

reg BEET income if year==2014 & pop2000>10, vce(robust)
est sto OLS_BIG

xtreg BEET income , be vce(bootstrap, reps(1000))
est sto BTW_ALL

xtreg BEET income if pop2000>10, be vce(bootstrap, reps(1000))
est sto BTW_BIG

reg BEET income b2014.year, vce(cluster id)
est sto POLS_ALL

reg BEET income b2014.year if pop2000>10, vce(cluster id)
est sto POLS_BIG

esttab OLS_ALL OLS_BIG BTW_ALL BTW_BIG POLS_ALL POLS_BIG, stats(N r2, fmt(0 3) label(N Rsq)) se label indicate("Time effects = *.year")

esttab OLS_ALL OLS_BIG BTW_ALL BTW_BIG POLS_ALL POLS_BIG using .\tables\regtable-beet, ///
	stats(N r2, fmt(0 3) label(N R2)) se label booktabs nofloat nonotes replace ///
	mtitle(OLS_ALL OLS_BIG BTW_ALL BTW_BIG POLS_ALL POLS_BIG) indicate("Time effects = *.year") 

*-------------------------------------------------------------------------------
* Scatter: Figure 3: Offshoring vs. Income, 2014 Snapshot (Net Onshoring, plots 1 and 2)
*-------------------------------------------------------------------------------

keep if year==2014

egen clocknetonshore = mlabvpos(netonshore income)

gr tw (lfit netonshore income, lcolor(gray)) (scatter netonshore income, mstyle(p1) mlabel(cc) mlabvpos(clocknetonshore)), ///
aspect(1) legend(off) ylabel(, angle(vertical)) ytitle("Net onshoring") xtitle(Income) ///
title("(1) Net onshoring, all countries", position(12)) 

gen markeryes = 0
replace markeryes = 1 if cc=="IND" | cc=="CYP" | cc=="MLT" | cc=="HRV" | cc=="CHN" | cc=="LTU" | cc=="DNK" | cc=="NLD" | cc == "NOR" | cc=="LUX" 

gr tw (lfit netonshore income, lcolor(gray)) (scatter netonshore income, mstyle(p1)) ///
(scatter netonshore income if markeryes==1, msymbol(none) mlabel(cc) mlabvpos(clocknetonshore)), ///
aspect(1) legend(off) ylabel(, angle(vertical)) ytitle("Net onshoring") xtitle(Income) ///
title("(1) Net onshoring, all countries", position(12)) name(all, replace)

replace clocknetonshore = 6 if cc=="BEL"
replace clocknetonshore = 6 if cc=="KOR"
replace clocknetonshore = 6 if cc=="GRC"
replace clocknetonshore = 6 if cc=="IDN"

gr tw (lfit netonshore income, lcolor(gray)) (scatter netonshore income, mstyle(p1) mlabel(cc) mlabvpos(clocknetonshore)) if pop2000>10, ///
aspect(1) legend(off) ylabel(, angle(vertical)) ytitle("Net onshoring") xtitle("Income") ///
title("(2) Net onshoring, large countries", position(12)) name(large, replace)

gr combine all large, ysize(4.5) xsize(9) row(1) scale(1.5) graphregion(margin(0 0 0 0))
gr export .\figures\scatter_offshoring_2014.pdf, replace

*-------------------------------------------------------------------------------
* Scatter: Figure 3: Offshoring vs. Income, 2014 Snapshot (BEET, plots 3 and 4)
*-------------------------------------------------------------------------------

keep if year==2014

egen clockBEET = mlabvpos(BEET income)

gr tw (lfit BEET income, lcolor(gray)) (scatter BEET income, mstyle(p1) mlabel(cc) mlabvpos(clockBEET)), ///
aspect(1) legend(off) ylabel(, angle(vertical)) ytitle("BEET") xtitle(Income) ///
title("(3) Net emission transfers, all countries", position(12)) 

gen markeryes = 0
replace markeryes = 1 if cc=="IND" | cc=="CYP" | cc=="LVA" | cc=="SWE" | cc=="CHN" | cc=="CHE" | cc=="TWN" | cc == "NOR" | cc=="LUX" 

gr tw (lfit BEET income, lcolor(gray)) (scatter BEET income, mstyle(p1) ) ///
(scatter BEET income if markeryes==1, msymbol(none) mlabel(cc) mlabvpos(clockBEET)), ///
aspect(1) legend(off) ylabel(, angle(vertical)) ytitle("BEET") xtitle(Income) ///
title("(3) Net emission transfers, all countries", position(12)) name(all, replace)

replace clockBEET = 3 if cc=="BEL"
replace clockBEET = 9 if cc=="FRA"
replace clockBEET = 3 if cc=="PRT"
replace clockBEET = 3 if cc=="TUR"
replace clockBEET = 6 if cc=="ROU"
replace clockBEET = 11 if cc=="HUN"
replace clockBEET = 3 if cc=="NLD"
replace clockBEET = 6 if cc=="AUS"

gr tw (lfit BEET income, lcolor(gray)) (scatter BEET income, mstyle(p1) mlabel(cc) mlabvpos(clockBEET)) if pop2000>10, ///
aspect(1) legend(off) ylabel(, angle(vertical)) ytitle("BEET") xtitle("Income") ///
title("(4) Net emission transfers, large countries", position(12)) name(large, replace)

gr combine all large, ysize(4.5) xsize(9) row(1) scale(1.5) graphregion(margin(0 0 0 0))
gr export .\figures\scatter_beet_2014.pdf, replace

*-------------------------------------------------------------------------------
* Scatter: Figure 4: Scale-Adjusted Net Onshoring (Balance of Avoided Emissions) vs. Income, 2014 Snapshot
*-------------------------------------------------------------------------------

keep if year==2014

egen clocknetonshore = mlabvpos(netonshore_sa income)

gr tw (lfit netonshore_sa income, lcolor(gray)) (scatter netonshore_sa income, mstyle(p1) mlabel(cc) mlabvpos(clocknetonshore)) , ///
aspect(1) legend(off) ytitle("Net onshoring, scale-adjusted") xtitle(Income) title("(1) All countries", position(12)) name(all, replace)

gen markeryes = 0
replace markeryes = 1 if cc=="IND" | cc=="CYP" | cc=="MLT" | cc=="HRV" | cc=="DNK" | cc == "NOR" | cc=="LUX" 

gr tw (lfit netonshore_sa income, lcolor(gray)) (scatter netonshore_sa income, mstyle(p1)) ///
(scatter netonshore_sa income if markeryes==1, msymbol(none) mlabel(cc) mlabvpos(clocknetonshore)) , ///
aspect(1) legend(off) ytitle("Net onshoring, scale-adjusted") xtitle(Income) title("(1) All countries", position(12)) name(all, replace)

replace clocknetonshore = 6 if cc=="KOR"
replace clocknetonshore = 8 if cc=="DEU"
replace clocknetonshore = 2 if cc=="CAN"
replace clocknetonshore = 3 if cc=="HUN"

gr tw (lfit netonshore_sa income, lcolor(gray)) (scatter netonshore_sa income, mstyle(p1) mlabel(cc) mlabvpos(clocknetonshore)) if pop2000>10, ///
aspect(1) legend(off) ytitle("Net onshoring, scale-adjusted") xtitle("Income") title("(2) Large countries", position(12)) name(large, replace)

gr combine all large, ysize(4.5) xsize(9) row(1) scale(1.5)  graphregion(margin(0 0 0 0))
gr export .\figures\scatter_offshoring_baltrade_2014.pdf, replace

*-------------------------------------------------------------------------------
* Values for Tables 6 and 7 (Appendix): Alternative estimation samples
*-------------------------------------------------------------------------------

reg netonshore income b2014.year, vce(cluster id)
regsave using regresults, tstat replace addlabel(desc, "All")

reg netonshore income b2014.year if pop2000>1, vce(cluster id)
regsave using regresults, tstat append addlabel(desc, "Pop<1m")

reg netonshore income b2014.year if pop2000>5, vce(cluster id)
regsave using regresults, tstat append addlabel(desc, "Pop<5m")

reg netonshore income b2014.year if pop2000>10, vce(cluster id)
regsave using regresults, tstat append addlabel(desc, "Pop<10m")

levelsof cc, local(cclist) 
foreach x of local cclist {
	reg netonshore income b2014.year if cc!="`x'", vce(cluster id)
	regsave using regresults, tstat append addlabel(desc, "`x'")
}

use regresults, clear

keep if var=="income"
drop if desc=="ZROW"
gen index = _n
gsort -index
drop var index
order desc

